import util from "../../utils/util";
import api from "../../utils/api";
import constant, {GATEWAY_HOST} from "../../utils/constant";

Page({
    data: {

        couponsCode: '',
        coupons: {},
        totalAmount: 0.0,
        payAmount: 0.0,
        couponsShow: false,
        carts: null,
        courseIdAndPrice: {}, // 存储课程id和对应价格的对象
        courseIds: [],
        MINIO_COURSE_COVER: constant.MINIO_COURSE_COVER,
        pageInfo: {pageNum: 1, pageSize: 8, totalPage: 0, totalRow: 0},
        payDialogShow: false,
        time: 15 * 60 * 1000,
        timeData: {},
        countDownShow: false,

        qrCodeImage: '',//二维码图片路径
        sn: '',//订单流水号


    },

    // 列表触底时追查下一页数据
    pageMore: function () {
        let that = this;
        let pageNum = that.data.pageInfo['pageNum'];
        let totalPage = that.data.pageInfo['totalPage'];
        if (pageNum < totalPage) {
            this.setData({'pageInfo.pageNum': this.data.pageInfo['pageNum'] + 1});
            this.page();
        }
    },

    // 分页查询购物车记录
    page: function () {
        let that = this;
        let pageNum = that.data.pageInfo['pageNum'];
        let pageSize = that.data.pageInfo['pageSize'];
        let userId = wx.getStorageSync('user').id;
        let params = {
            pageNum: pageNum,
            pageSize: pageSize,
            'fkUserId': userId
        };
        api.get('cart', '/page', params).then(res => {
            that.setData({
                'carts': pageNum === 1 ? res['records'] : that.data.carts.concat(res['records']),
                'pageInfo.pageNum': res['pageNumber'],
                'pageInfo.pageSize': res['pageSize'],
                'pageInfo.totalPage': res['totalPage'],
                'pageInfo.totalRow': res['totalRow'],
            });
            // 将课程id和对应价格存入 courseIdAndPrice 变量
            let courseIdAndPrice = {};
            for (let i in that.data.carts) {
                let cart = that.data.carts[i];
                courseIdAndPrice[cart['fkCourseId']] = cart['coursePrice'];
            }
            that.setData({'courseIdAndPrice': courseIdAndPrice});
        }).catch(err => console.error(err));
    },



    // 兑换优惠卷
    getCoupons: function (ev) {
        let code = ev.detail;
        // if (!this.data.carts || this.data.carts.length <= 0) {
        //     util.error('购物车记录为空');
        //     return;
        // }
        if (code) {
            let url = '/selectByCode/' + code;
            api.get('coupons', url).then(res => {
                res['endTime'] = util.dateFormat(res['endTime']);
                res['startTime'] = util.dateFormat(res['startTime']);
                res['created'] = util.dateFormat(res['created']);
                res['updated'] = util.dateFormat(res['updated']);
                this.setData({
                    'couponsCode': '',
                    'coupons': res,
                    'payAmount': this.data.totalAmount - res['cpPrice'],
                    'couponsShow': true,
                });
                util.success('优惠卷已生效');
            }).catch(err => util.error('优惠卷无效', err));
        }
    },

    // 选择课程时触发
    changeCourseIds: function (ev) {
        let courseIds = ev.detail;
        this.setData({'courseIds': courseIds});
        // 从 courseIdAndPrice 中获取当前选中的全部课程的价格
        let courseIdAndPrice = this.data.courseIdAndPrice;
        let payAmount = 0;
        let totalAmount = 0;
        for (let i in courseIds) {
            let courseId = courseIds[i];
            payAmount += courseIdAndPrice[courseId];
            totalAmount += courseIdAndPrice[courseId];
        }
        this.setData({payAmount, totalAmount});
    },

    // 删除购物车记录
    removeCart: function (ev) {
        let id = ev.currentTarget.dataset['id'];
        util.confirm('课程将被移出购物车，确定吗？', () => {
            api.del('cart', `/delete/${id}`).then(res => {
                util.success('移出成功');
                this.setData({'carts': null});
                this.page();
            }).catch(err => console.log(err));
        });
    },

    // 清空购物车记录
    clearCart: function (ev) {
        util.confirm('清空购物车中的全部课程，确定吗？', () => {
            let url = '/clearByUserId/' + wx.getStorageSync('user').id;
            api.del('cart', url).then(res => {
                util.success('清空成功');
                this.setData({
                    'carts': null,
                    'totalAmount': 0.0,
                    'payAmount': 0.0,
                    'coupons': null,
                });
            }).catch(err => console.log(err));
        });
    },




    // 当倒计时结束时触发
    onCountDownFinish: function (ev) {
        util.error('支付超时');
        this.setData({
            'payDialogShow': false,
            'countDownShow': false
        });
    },


    // 倒计时
    countDown: function (ev) {
        this.setData({'timeData': ev.detail});
    },

// 打开支付对话框
    openPayDialog: function () {

        let that = this;

        // 若选择内容为空，则不进行支付动作
        if (this.data.courseIds.length <= 0) {
            util.error('至少选择一项');
            return;
        }

        // 发送预支付请求
        let params = {
            'fkUserId': wx.getStorageSync('user').id,
            'courseIds': this.data.courseIds,
            'totalAmount': this.data.totalAmount,
            'payAmount': this.data.payAmount,
            'fkCouponsId': this.data.coupons['id'] ? this.data.coupons['id'] : null,
        };
        api.post('order', '/prePay', params).then(res => {

            this.setData({'sn':res})

            // 获取支付二维码
            wx.request({
                url: GATEWAY_HOST + '/order-server/api/v1/order/getQrCode',
                method: 'POST',
                data: {
                    'sn': that.data.sn,
                    'payAmount': this.data.payAmount
                },
                header: {'token': wx.getStorageSync('token')},
                responseType: 'arraybuffer',
                success(res) {
                    if (res.statusCode !== 200) {
                        util.error('获取二维码失败');
                        return;
                    }
                    // 显示二维码
                    that.setData({
                        'qrCodeImage': 'data:image/png;base64,' + wx.arrayBufferToBase64(res.data),
                        'payDialogShow': true,
                        'countDownShow': true
                    });

                    // 每隔2秒钟轮询查询订单状态
                    let timer = setInterval(function () {
                        api.get('order', '/checkStatusBySn/' + that.data.sn).then(res => {
                            if (res === true) {
                                util.success('支付成功');
                                clearInterval(timer);
                                that.setData({
                                    'payDialogShow': false,
                                    'countDownShow': true
                                });
                                // 跳转到订单页面
                                util.page('/pages/order/order');
                            }
                        }).catch(err => util.error('查询订单状态失败', err));
                    }, 2000);
                },
            });
        }).catch(err => console.log(err));
    },

    // 关闭支付对话框
    closePayDialog: function () {
        this.setData({
            'payDialogShow': false,
            'countDownShow': false
        });
    },

    // 打开优惠卷面板
    openCouponsSheet: function () {
        this.setData({'couponsShow': true});
    },

    // 关闭优惠卷面板
    closeCouponsSheet() {
        this.setData({'couponsShow': false});
    },

    // 加载函数
    onLoad: function (options) {
        if (util.isLogin()) {
            this.page();
        }
        this.getTabBar().setData({"activeTab": 2});
    }
})